package com.water.dynamic;

import com.water.aop.Aop;
import com.water.service.IService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author wsj
 * @version 1.0
 * @description: TODO
 * @date 2022/1/9 23:29
 */
public class ProxyFactor {
    private IService service;//被代理对象
    private Aop aop;//切面

    public ProxyFactor(IService service, Aop aop){
        this.service = service;
        this.aop = aop;
    }

    public Object getProxyInstance(){
        return Proxy.newProxyInstance(
                service.getClass().getClassLoader(),
                service.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try{
                            aop.before();
                            Object invoke = method.invoke(service, args);
                            aop.after();
                            return invoke;
                        }catch (Exception e){
                            aop.exception();
                            e.printStackTrace();
                            throw e;
                        }finally {
                            aop.myFinally();

                        }
                    }
                }
        );
    }
}
